package com.doradance.common.web;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.pachong.android.baseuicomponent.CompState;
import com.pachong.android.baseuicomponent.fragment.BaseFragment;
import com.pachong.android.framework.R;
import com.pachong.android.framework.web.ActivityResultTransferable;
import com.pachong.android.framework.web.X5CommonWebview;
import com.pachong.android.frameworkbase.utils.SLog;
import com.tencent.smtt.export.external.interfaces.SslError;
import com.tencent.smtt.export.external.interfaces.SslErrorHandler;
import com.tencent.smtt.export.external.interfaces.WebResourceRequest;
import com.tencent.smtt.export.external.interfaces.WebResourceResponse;
import com.tencent.smtt.sdk.WebSettings;

import java.util.HashMap;
import java.util.Map;

/**
 * 通用的WebviewFragment
 *
 * @Author: PV
 * @E-mail: pengveivei@sina.cn
 * @CreateDate: 2016-09-09
 * @Version: 1.0.0
 */
public class X5CommonWebviewFragment extends BaseFragment {
    private X5CommonWebview mWebView;
    private static final String KEY_URL = "URL";
    private String mUrl;
    private Map<String, Object> mJspInterfaceMap = new HashMap<>();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = super.onCreateView(inflater, container, savedInstanceState);
//        initWebView();
        if (getArguments() != null) {
            mUrl = getArguments().getString(KEY_URL);
            if (!TextUtils.isEmpty(mUrl)) {
                mWebView.getSettings().setAppCacheEnabled(true);
                mWebView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
//                mWebView.getSettings().setBlockNetworkImage(true);
                mWebView.loadUrl(mUrl);

            }
        }
        Log.e("vivi", "  mWebView.loadUrl(mUrl);   " + mUrl);
//        setupWebview();
        return view;
    }

//    private void setupWebview() {
//        getWebview().setWebViewClient(new WebViewClient() {
//            public boolean shouldOverrideUrlLoading(WebView view, String url) {
//                // 拦截html电话请求
//                if (url.startsWith("tel:")) {
//                    tel(view.getContext(), url);
//                    return true;
//                }
////
//                Log.e("kyluzoi", "shouldOverrideUrlLoading  load url == " + url);
//                if (isMyApi(url)) {
//                    return true;
//                }
//
//                // CommonWebview.this.loadUrl(url);
//                // 消耗掉这个事件。Android中返回True的即到此为止吧,事件就会不会冒泡传递了，我们称之为消耗掉
//                // return true;
//                return true;
//            }
//
//            public void onPageFinished(WebView view, String url) {
//                super.onPageFinished(view, url);
//                if (getState() != CompState.EMPTY_ERROR && getState() != CompState.EMPTY_INVALID_NEWWORK) {
//                    setState(CompState.DATA);
//                }
//            }
//
//            public void onPageStarted(WebView view, String url, Bitmap favicon) {
//                super.onPageStarted(view, url, favicon);
//            }
//
//            @Override
//            public void onLoadResource(WebView view, String url) {
//                super.onLoadResource(view, url);
//            }
//
//            @Override
//            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
//                super.onReceivedError(view, errorCode, description, failingUrl);
//                Log.e("vivi", "  onReceivedError errorCode = " + errorCode + " description == " + description);
//                // -2 网络断开，或者ERR_ADDRESS_UNREACHABLE
//                // -5 Authentication via the proxy server was unsuccessful
//                // -1 There was a network error.  请求数据过程中中断网络
//                if (errorCode == -2 || errorCode == -5 || errorCode == -1) {
//                    setState(CompState.EMPTY_INVALID_NEWWORK);
//                }
//            }
//
//            @Override
//            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
//                super.onReceivedSslError(view, handler, error);
//                handler.proceed();
//            }
//
//            @Override
//            public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
//                super.onReceivedHttpError(view, request, errorResponse);
//            }
//
//            @Override
//            public void onReceivedError(WebView view, WebResourceRequest request, WebViewClient.a error) {
//                super.onReceivedError(view, request, error);
//            }
//        });
//    }


    /**
     * 拨打电话
     *
     * @param context
     * @param tel
     */
    public static void tel(Context context, String tel) {
        if (!TextUtils.isEmpty(tel)) {
            Intent intent_phone = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + tel));
            intent_phone.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent_phone);
        }
    }



    public static X5CommonWebviewFragment newInstance(String url) {
        Bundle args = new Bundle();
        args.putString(KEY_URL, url);
        X5CommonWebviewFragment fragment = new X5CommonWebviewFragment();
        fragment.setArguments(args);
        return fragment;
    }

//    protected void initWebView() {
//        mWebView.init(this);
//        // addJavascriptInterface
//        addJavascriptInterface(new MobileFunImpl(this), "WebAppJS");//mobile 是与前端定义的一个方法协议
//    }
//
//    public WebView getWebview() {
//        return mWebView;
//    }
//
//    @SuppressLint("JavascriptInterface")
//    protected void addJavascriptInterface(Object obj, String name) {
//        mWebView.addJavascriptInterface(new MobileFunImpl(this), "WebAppJS");//mobile 是与前端定义的一个方法协议
//        mWebView.addJavascriptInterface(obj, name);
//        mJspInterfaceMap.put(name, obj);
//
//    }

    @Override
    public View createDataView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_x5_common_webview, null);
        mWebView = (X5CommonWebview) view.findViewById(R.id.webView);
        return view;
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        // 转发给webview
        mWebView.onActivityResult(requestCode, resultCode, data);

        // 转发给JspInterface对象
        for (Map.Entry<String, Object> entry : mJspInterfaceMap.entrySet()) {
            if(entry.getValue() instanceof ActivityResultTransferable) {
                ActivityResultTransferable art = (ActivityResultTransferable) entry.getValue();
                art.onActivityResult(requestCode, resultCode, data);
            }
        }
    }

  /*  //region   业务逻辑模块，填如js接口对象中


    *//**
     * eventbus 登录成功后调用该方法回调web
     *
     * @param event
     *//*
    @Subscribe(threadMode = ThreadMode.BACKGROUND)
    public void onLogin(ClassEvent.WebEvent event) {
        mWebView.loadUrl("javascript:onLogin()");
    }


    private void clipImage(String url, String outputUrl) {
        mFilename = "/" + System.currentTimeMillis() + ".png";
        PhotoActionHelper.clipImage(getActivity())
                .input(url)
                .output(outputUrl + mFilename)
                .maxOutputWidth(320)
                .requestCode(REQUEST_CLIP)
                .start(this);
    }

    @Override
    public void btnPictureClick() {
        Intent intent_TP = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        mImageUri = TakePhoto.getInstance().getOutputMediaFileUri(getActivity().getBaseContext());
        intent_TP.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);
        startActivityForResult(intent_TP, TAKE_PHOTO_REQUEST);
    }


    @Override
    public void btnPhotoClick() {
        Intent intentPickPhoto = new Intent(getActivity(), SelectAlbumActivity.class);
        intentPickPhoto.putExtra(SelectAlbumActivity.RELEASE_IMGS_NUM, 0);
        intentPickPhoto.putExtra(SelectAlbumActivity.INTENT_MAX_NUM, 1);
        startActivityForResult(intentPickPhoto, SELECT_ALBUM_REQUEST);
    }

    @Override
    public void setTabBar(final int isShow) {
        try {
            final Fragment fragment = getParentFragment();
            fragment.getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    RadioGroup rgBottomMenu = (RadioGroup) fragment.getActivity().findViewById(com.pachong.android.framework.R.id.rg_bottom);
                    rgBottomMenu.setVisibility(isShow);
                    View view = fragment.getActivity().findViewById(com.pachong.android.framework.R.id.vp_home);
                    view.requestLayout();
                    view.invalidate();
                }
            });

        } catch (NullPointerException e) {
            Log.e("kyluzoi", "can't not findViewByid with tab");
        }
    }

    //endregion */

/*
    @Override
    public View createEmptyInvalidNetView(LayoutInflater inflater) {
        View view = inflater.inflate(R.layout.empty_invalid_net, null);
        view.findViewById(R.id.btnRefresh).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mWebView.reload();
                setState(CompState.EMPTY_REFRESHING);
            }
        });
        return view;
    }


    @Override
    public View createEmptyRefreshingView(LayoutInflater inflater) {
        return inflater.inflate(R.layout.empty_refreshing, null);
    }*/
}
